<?php

$ROOT_PATH = dirname(__DIR__).'/';

require_once $ROOT_PATH.'vendor/autoload.php';
require_once $ROOT_PATH.'lib/func.php';

use Medoo\Medoo;

$db_config = require_once $ROOT_PATH.'config/db.php';

$dataPath = $argv[1];
if (empty($dataPath)){
    var_dump('数据路径不存');
    exit();
}

$book = json_decode(file_get_contents($dataPath), true);
if (empty($book)){
    var_dump('没有数据');
    exit();
}

$db = new Medoo($db_config);

$change = [
    '出版社' => 'publish',
    'ISBN' => 'isbn',
    '版次' => 'edition',
    '商品编码' => 'goods_code',
    '包装' => 'package',
    '开本' => 'format',
    '出版时间' => 'publish_date',
    '用纸' => 'form',
    '正文语种' => 'main_language',
    '品牌' => 'brand',
    '丛书名' => 'series_name',
    '外文名称' => 'foreign_name',
    '页数' => 'page_number',
    '字数' => 'word_number',
    '附件' => 'attach',
    '附件数量' => 'attach_number',
    '套装数量' => 'suit_number',
];

$info = explode("\n", $book['info']);
if (!empty($info)){
    $delimiter = '：';
    $res = [
        'title' => trim($book['title']),
        'category' => trim(str_replace([" ", "\n"], '', $book['category'])),
        'author' => trim($book['author']),
        'cover' => trim($book['cover']),
    ];
    foreach ($info as $k => $v){
        if (empty($v)){
            continue;
        }
        if (stripos($v, $delimiter) !== false){
            $itemArr = explode($delimiter, $v);
            if (empty($itemArr[1])){
                if (!empty($info[$k + 1])){
                    $res[$change[str_replace($delimiter, '', $itemArr[0])]] = trim($info[$k + 1]);
                }
            } else {
                $res[$change[str_replace($delimiter, '', $itemArr[0])]] = $itemArr[1];
            }
        }
    }
    var_dump($res);
    if (empty($db->get('book', 'isbn', ['isbn' => $res['isbn']]))){
        $db->insert('book', $res);
    }
}

